import i18n from '@/lang/lang'

const install = (Vue, vm) => {
  let getSystemInfoSync = uni.getSystemInfoSync()
  if (!uni.getStorageSync('baseUrl')) {
    uni.setStorageSync('baseUrl', 'https://webv2.qstamper.com/stamper/apis')
  }
  Vue.prototype.$u.http.setConfig({
    // http://210.45.123.183:8081
    // http://47.101.200.110/stamper/apis
    // https://qstamper.com
    baseUrl: process.env.NODE_ENV == 'development' && !getSystemInfoSync.version ? uni.getStorageSync('baseUrl') : uni.getStorageSync('baseUrl'),
    loadingText: i18n.t('努力加载中') + '~',
    loadingTime: 4000,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'us': 'app',
      // #ifdef H5
      'Yx-Origin': location.origin,
      // #endif
    },
  });
  // uni.setStorageSync('baseUrl', 'https://qstamper.com');
  // 请求拦截部分，如配置，每次请求前都会执行
  Vue.prototype.$u.http.interceptor.request = (config) => {
    console.log('请求拦截', config.url)
    config.header.Authorization = vm.$store.state.user.userToken;
    //判断用户有没有登录
    let arr = [
      '/auth/org/getOrgsByPhone',
      '/auth/user/loginV1',
      '/auth/org/dir',
      '/auth/strategypassword/getTipsByCode',
      '/auth/user/getPhoneCode',
      '/auth/user/reg',
      '/auth/user/resetPwd',
      '/auth/strategypassword/check',
    ]
    if (arr.includes(config.url)) {//此接口不需要验证token
      return true
    } else {
      if (!vm.$store.state.user.userToken) {
        uni.reLaunch({
          url: '/pages/template/login/login'
        })
        return false
      }
    }
    // 最后需要将config进行return
    return config;
    // 如果return一个false值，则会取消本次请求
    // if(config.url == '/user/rest') return false; // 取消某次请求
  }
  // 响应拦截，如配置，每次请求结束都会执行本方法
  Vue.prototype.$u.http.interceptor.response = (res, err) => {
    if (res.code == 200) {
      return res;
    } else if ((res.code < 700 && res.code > 600) || res.code == 600) { //大于600跳登录
      uni.showToast({
        icon: 'none',
        title: res.msg
      });
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/template/login/login'
        })
      }, 1500)
      return false;
    } else if (res.code == 599) {
      uni.showModal({
        title: '提示',
        content: res.msg,
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/template/personaInfo/personaInfo'
            });
          }
        }
      });
    } else {
      uni.showToast({
        icon: 'none',
        title: res.msg || '当前服务不可用',
        duration: 2000
      });
      return res
    }
  }
}

export default {
  install
}
